package com.moriarty.socketim.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.moriarty.socketim.IMApplication;
import com.moriarty.socketim.R;
import com.moriarty.socketim.core.OnMessageListener;
import com.moriarty.socketim.entity.BuddyInfo;
import com.moriarty.socketim.entity.QQMessage;
import com.moriarty.socketim.entity.QQMessageType;
import com.moriarty.socketim.util.ThreadUtil;

import java.util.ArrayList;

/**
 * Created by Moriarty on 16/11/17.
 */

public class ChatActivity extends BaseActivity implements View.OnClickListener {

    private TextView mTvChatTitle;
    private EditText mEtChatinput;
    private Button mBtnSendchat;
    private IMApplication imApplication;
    private BuddyInfo mBuddyInfo;
    private ListView mLvChat;
    private ArrayList<QQMessage> listChat = new ArrayList<QQMessage>();
    private ChatAdapter mChatAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_chat);

        Intent intent = getIntent();
        mBuddyInfo = (BuddyInfo) intent.getSerializableExtra("buddyInfo");

        mTvChatTitle = (TextView) findViewById(R.id.tv_chattitle);
        mEtChatinput = (EditText) findViewById(R.id.et_chatinput);
        mLvChat = (ListView) findViewById(R.id.lv_chat);//核心listview 对话内容
        mChatAdapter = new ChatAdapter();
        mLvChat.setAdapter(mChatAdapter);
        mBtnSendchat = (Button) findViewById(R.id.btn_sendchat);

        mBtnSendchat.setOnClickListener(this);

        mTvChatTitle.setText("chatting with " + mBuddyInfo.getNick() + " now");

        imApplication = (IMApplication) getApplication();
        //一创建activity就准备好监听
        imApplication.getQqConnection().addOnMessageListener(listener);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sendchat:

                final String input = mEtChatinput.getText().toString().trim();
                ThreadUtil.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (input.equals("")) {
                            Toast.makeText(getApplicationContext(), "cannot send empty message!", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                final QQMessage qqMessage = new QQMessage();
                qqMessage.type = QQMessageType.MSG_TYPE_CHAT_P2P;
                qqMessage.from = Long.parseLong(imApplication.getUsername());
                qqMessage.to = mBuddyInfo.getAccount();
                qqMessage.content = input;
                ThreadUtil.runOnSubThread(new Runnable() {
                    @Override
                    public void run() {
                        imApplication.getQqConnection().sendMessage(qqMessage);
                        listChat.add(qqMessage);//发送成功以后 存入列表 为显示准备素材
                        ThreadUtil.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mChatAdapter != null) {
                                    mChatAdapter.notifyDataSetChanged();
                                    mLvChat.setSelection(listChat.size() - 1);//在发出和接收消息之后要自动滚动到最后一行
                                    mEtChatinput.setText("");
                                    /**隐藏软键盘**/
                                    View view = getWindow().peekDecorView();
                                    if (view != null) {
                                        InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                        inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
                                    }
                                }
                            }
                        });
                    }
                });
                break;
        }
    }

    private OnMessageListener listener = new OnMessageListener() {
        @Override
        public void onGetMessage(final QQMessage msg) {
            ThreadUtil.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    if (QQMessageType.MSG_TYPE_CHAT_P2P.equals(msg.type)) {
                        listChat.add(msg);//接收以后存入列表 为显示准备素材
                        if (mChatAdapter != null) {
                            mChatAdapter.notifyDataSetChanged();
                            mLvChat.setSelection(listChat.size() - 1);//在发出和接收消息之后要自动滚动到最后一行
                        }
                    }
                }
            });
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        imApplication.getQqConnection().removeOnMessageListener(listener);
    }

    private class ChatAdapter extends BaseAdapter {
        //用于getView里面 区分不同的item
        @Override
        public int getItemViewType(int position) {

            QQMessage latestMsg = listChat.get(position);
            if (latestMsg.from == Long.parseLong(imApplication.getUsername())) {//如果是自己说的
                return 0;
            } else {//如果不是自己说的
                return 1;
            }
        }

        @Override
        public int getViewTypeCount() {

            return 2;//两种 一种是别人 一种是我自己
        }

        @Override
        public int getCount() {
            return listChat.size();
        }

        @Override
        public Object getItem(int position) {
            return listChat.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            int itemViewType = getItemViewType(position);
            int layoutId = 0;
            if (itemViewType == 0) {//说明来自自己
                layoutId = R.layout.item_chat_me;
            } else {//说明来自别人
                layoutId = R.layout.item_chat_buddy;
            }
            convertView = setChatListItem(position, convertView, layoutId);
            return convertView;
        }

        @NonNull
        private View setChatListItem(int position, View convertView, int layoutId) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = View.inflate(getApplicationContext(), layoutId, null);
                viewHolder = new ViewHolder();
                viewHolder.iv_header = (ImageView) convertView.findViewById(R.id.iv_chat_head);
                viewHolder.tv_chat_time = (TextView) convertView.findViewById(R.id.tv_chat_time);
                viewHolder.tv_content = (TextView) convertView.findViewById(R.id.tv_chat_content);

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            QQMessage qqMessage = (QQMessage) (getItem(position));
            viewHolder.iv_header.setImageResource(qqMessage.fromAvatar == 0 ? R.drawable.ic_launcher : qqMessage.fromAvatar);
            viewHolder.tv_chat_time.setText(qqMessage.sendTime);
            viewHolder.tv_content.setText(qqMessage.content);
            return convertView;
        }

        class ViewHolder {
            ImageView iv_header;
            TextView tv_content;
            TextView tv_chat_time;
        }
    }
}
